package com.starinside.wp.interceptor;

import com.starinside.wp.components.MemVerificationCache;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.repository.WxUserRepository;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.LiveRoomService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

import static com.starinside.wp.foundation.constant.CommonConstant.Platform.WXMP;
import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxUserRepository userRepository;

    @Autowired
    private BindedBabyService bindedBabyService;

    @Autowired
    private LiveRoomService liveRoomService;

    @Autowired
    private MemVerificationCache cache;

    @Value("${com.matt.enableDefaultUser}")
    private boolean enableDefaultUser;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {

        String url = httpServletRequest.getRequestURI();
        if( !url.startsWith("/wx/") && !url.startsWith("/web/")
                && !url.startsWith("/pad/")  && !url.startsWith("/api/")
                && !url.startsWith("/v2/")){
            return true;
        }

        if(url.startsWith("/wx/api/portal") || url.startsWith("/wx/portal")
                || url.startsWith("/wx/push") || url.startsWith("/wx/menu")
//                || url.startsWith("/wx/partner")
                || url.startsWith("/v2/op/appform")
                ||  url.startsWith("/api/children_month_record") || url.startsWith("/eapi/bmi")
                || url.startsWith("/wx/api/vendor_courseV2") || url.startsWith("/api/op/shop")){
            return true;
        }

        String ticket = httpServletRequest.getHeader(TICKET);

        WxUser loginUser = (WxUser) httpServletRequest.getSession().getAttribute("loginUser");

        //之前是用ticket登录的
        if (StringUtils.isNotEmpty(ticket) && loginUser != null){
            if (!ticket.equals(loginUser.getTicket())){
                httpServletRequest.getSession().removeAttribute("loginUser");
                loginUser = null;
            }
        }

        if( loginUser != null){
            return true;
        }

        if (StringUtils.isNotEmpty(ticket)){
            this.logger.info("auth with ticket:{}", ticket);

            String staffId = cache.getWxUserId(ticket);
            Optional<WxUser> optional = userRepository.findById(staffId);
            if (!optional.isPresent()){
                this.logger.info("not found any user by ticket ");
                return false;
            }

            WxUser wxUser = optional.get();

            this.logger.info("auth user:{}", wxUser.getId());

            attachResource(wxUser);

            httpServletRequest.getSession().setAttribute("loginUser", wxUser);

            return true;
        }
//        enableDefaultUser &&
        if( StringUtils.isNotEmpty(httpServletRequest.getQueryString())
                && httpServletRequest.getQueryString().contains("testUser=1")){

            Optional<WxUser> optionalWxUser = userRepository.findByOpenidWp("o75Fe57Tg9zGSi8jLQvnt5Tlb-lc");

            if(!optionalWxUser.isPresent()){
            }else{
                WxUser wxUser = optionalWxUser.get();
                this.logger.info("findByOpenId:{}", o);

                attachResource(wxUser);

                //给测试用户创建ticket
                ticket = cache.produceTicket(wxUser.getId(), WXMP.codeOf());
                wxUser.setTicket(ticket);

                httpServletRequest.getSession().setAttribute("loginUser", wxUser);

                logger.debug("use debug user as " + wxUser.getParentMobile());
            }

            return true;
        }

        logger.info("refuse url without auth user :" + url);

//        throw new BusinessException(ErrorCode)
        throw new BusinessException(ErrorCode.SESSION_TOKEN_ERROR,  "登录已过期，请重新登录" );
//        return false;
    }

    private void attachResource(WxUser user){
        if (StringUtils.isEmpty(user.getDefaultBabyId())){

            List<BindedBabyVO> babies = bindedBabyService.getAllBindedBaby(user.getParentMobile());

            if(babies == null || babies.size() == 0){
//                throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST,"当前账号下没有宝宝信息");
            }else{
                //没有默认宝宝
                user.setDefaultBaby(babies.get(0));
                user.setDefaultBabyId(babies.get(0).getId());

                userRepository.save(user);
            }

        }

        if(user.getParentMobile() != null && user.getDefaultBabyId() != null){
            BindedBabyVO defaultBaby = bindedBabyService.getBindedBaby(user.getDefaultBabyId(), user.getParentMobile());
            user.setDefaultBaby(defaultBaby);
        }

        user.setLiveroomValid(liveRoomService.childrenCameraValid(user.getParentId(), bindedBabyService.getAllBindedBaby(user.getParentMobile())));
    }
}